import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { join } from 'path'
import { writeFileSync } from 'fs'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// 默认读取生产条件下的环境变量xx
const antPrefix = loadEnv('product', process.cwd())['VITE_ANTD_PREFIX']
const poxyUrl = 'https://asa-qa.allintechinc.com'
const crmPoxyUrl = 'https://asa-qa.allintechinc.com'
// const poxyUrl = 'http://asa-qa.allintechinc.com/'

export default defineConfig({
  base: '/app_50000005/',
  plugins: [
    vue(),
    vueJsx(),
    VueI18nPlugin({
      include: resolve(__dirname, './src/locales/**.json')
    }),
    (function () {
      let basePath = ''
      return {
        name: 'vite:micro-app',
        apply: 'build',
        configResolved(config) {
          basePath = `${config.base}${config.build.assetsDir}/`
        },
        writeBundle(options, bundle) {
          for (const chunkName in bundle) {
            if (Object.prototype.hasOwnProperty.call(bundle, chunkName)) {
              const chunk = bundle[chunkName]
              if (chunk.fileName && chunk.fileName.endsWith('.js')) {
                chunk.code = chunk.code.replace(
                    /(from|import\(?)(\s*['"])(\.\.?\/)/g,
                    (all, $1, $2, $3) => {
                      const u = new URL($3, 'http://tmp.com' + basePath)
                      // return all.replace($3, new URL($3, basePath));
                      return all.replace($3, u.pathname)
                    }
                )
                const fullPath = join(options.dir, chunk.fileName)
                writeFileSync(fullPath, chunk.code)
              }
            }
          }
        }
      }
    })(),
    createSvgIconsPlugin({
      iconDirs: [resolve(process.cwd(), 'src/assets/icons')],
      svgoOptions: true,
      // default
      symbolId: 'icon-[dir]-[name]'
    })
  ],
  resolve: {
    alias: [
      { find: '@', replacement: resolve(__dirname, 'src') },
      {
        find: '@antv/x6',
        replacement: '@antv/x6/lib'
      },
      {
        find: '@antv/x6-vue-shape',
        replacement: '@antv/x6-vue-shape/lib'
      }
    ]
  },
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        modifyVars: {
          'ant-prefix': antPrefix,
          hack: `true; @import (reference) "${resolve('src/design/custom-theme.less')}";`
        },
        additionalData: `@import "${resolve(__dirname, 'src/design/base.less')}";`
      }
    }
  },
  server: {
     port: 3100,
    proxy: {
            '/solution-ppm/api/v2': {
                // target: 'http://10.10.0.201:8081',
                // target: 'http://10.20.0.203:8081',
                // target: 'http://10.10.0.174:8081',
                target: poxyUrl,
                // changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            },
            '/solution-ppm-work-order/api/v1': {
                // target: 'http://10.10.0.201:8081',
                // target: 'http://10.20.0.80:8082',
                // target: 'http://10.20.0.203:8083',
                target: poxyUrl,
                // changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            },
            '/solution-crm/api/v1': {
                // target: 'http://10.20.0.203:8082',
                // target: 'http://10.10.0.119:8081',
                // target: 'http://10.10.0.119:8082',
                target: crmPoxyUrl,
                // changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            },
            '/file-storage/api/v1/file/upload': {
                target: poxyUrl,
                changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            },
            '/config.json': {
                target: poxyUrl,
                changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            },
            '/base/api/v1': {
                target: poxyUrl,
                changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            },
            '/file-storage/api/v1': {
                target: poxyUrl,
                changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            },
            '/workflow-platform/api/v1': {
                target: poxyUrl,
                changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            }
        }
  },
  assetsInclude: ['**/*.bmp'],
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            const names = id.split('node_modules/')
            const lastPath = names[names.length - 1]
            return '_lib_' + lastPath.split('/')[0].replace('@', '_')
          }
        }
      }
    },
    terserOptions: {
      compress: {
        drop_debugger: true
      }
    }
  }
})